﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UMLTouch.DomainRecognition.Factory;
using System.Collections.ObjectModel;
using System.IO;
using System.Reflection;
using UMLTouch.UI.Start.ViewModels;
using System.Windows;
using UMLTouch.UI.Start.Properties;

namespace UMLTouch.UI.Start.ViewModels
{
    public class DomainRecognitionCollection : ObservableCollection<DomainRecognitionViewModel>
    {
        public DomainRecognitionCollection()
            :base()
        {

        }

        public static DomainRecognitionCollection Load(String pluginPath)
        {
            DomainRecognitionCollection ret = new DomainRecognitionCollection();


            if (Directory.Exists(pluginPath))
            {
                String[] diagramsDirectory = Directory.GetFiles(pluginPath, "*.dll");

                foreach (String s in diagramsDirectory)
                {
                    Assembly tmp = System.Reflection.Assembly.LoadFrom(s);
                    var types = tmp.GetTypes().Where(t =>
                           t.GetInterfaces().Any(t2 => t2.Equals(typeof(IDomainRecognition)))
                        );
                    if (types.Count() > 0)
                    {
                        foreach (Type t in types)
                        {
                            IDomainRecognition item = Activator.CreateInstance(t) as IDomainRecognition;
                            String name = t.Name;
                            if (item != null && !name.Equals(String.Empty))
                            {
                                DomainRecognitionViewModel model = new DomainRecognitionViewModel(item);
                                ret.Add(model);
                                foreach (var res in item.ResourceFiles)
                                {
                                    LoadResources(tmp.FullName, res);
                                }

                            }
                        }
                    }
                }
            }



            return ret;
        }


        static void LoadResources(String assemblyName, String resourceName)
        {
            string packUri = String.Format(@"/{0};component/{1}", assemblyName, resourceName);

            Uri uri = new Uri(packUri, UriKind.Relative);


            ResourceDictionary dic = Application.LoadComponent(uri) as ResourceDictionary;
            Application.Current.Resources.MergedDictionaries.Add(dic);
        }


    }
}
